package com.baidu.foodrecipe.ui.fragment.favorite

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.baidu.foodrecipe.R
import com.baidu.foodrecipe.base.BaseFragment
import com.baidu.foodrecipe.databinding.FragmentFavoriteHomeBinding
import com.baidu.foodrecipe.ui.adapters.FavoriteAdapter
import kotlin.getValue


class FavoriteHomeFragment : BaseFragment<FragmentFavoriteHomeBinding>() {
    private val viewModel: FavoriteViewModel by activityViewModels()
    private val mAdapter = FavoriteAdapter()

    override fun initUI(savedInstanceState: Bundle?) {
        super.initUI(savedInstanceState)

        viewModel.favoriteRecipes.observe(viewLifecycleOwner) {
            mAdapter.setNewData(it)
        }
        mBinding.recyclerView.adapter = mAdapter
        mBinding.recyclerView.layoutManager = LinearLayoutManager(requireActivity())


        //绑定删除所有的事件
        mBinding.tvDelete.setOnClickListener {
            viewModel.deleteAllFavorites()
        }

        //添加左右滑动删除
        val callBackImpl = ItemTouchHelperCallBackImpl(viewModel)
        val touchHelper = ItemTouchHelper(callBackImpl)
        touchHelper.attachToRecyclerView(mBinding.recyclerView)
    }

    /*
    ItemTouchHelper支持两种事件  滑动和拖拽
     */
    private class ItemTouchHelperCallBackImpl(val viewModel: FavoriteViewModel) :
        ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
        override fun onMove(
            recyclerView: RecyclerView,
            viewHolder: RecyclerView.ViewHolder,
            target: RecyclerView.ViewHolder
        ): Boolean {
            //拖动时回调的方法
            return false
        }

        override fun onSwiped(
            viewHolder: RecyclerView.ViewHolder,
            direction: Int
        ) {
            //滑动时回调的方法
            //通过viewHolder对象获取当前滑动的item的position
            val position = viewHolder.adapterPosition

            //删除数据源
            viewModel.removeFavoriteRecipe(position)
        }

    }
}